package com.aidex.common.utils.fb;
import org.firebirdsql.ds.FBSimpleDataSource;
import java.io.*;
import java.sql.*;

public class FBJDBCUtils {
    public static Connection getConn() {
            FBSimpleDataSource dataSource =
                    new FBSimpleDataSource();
        //  jdbc:firebirdsql://localhost/C:/database/employee.fdb?lc_ctype=UTF8
        //  dataSource.setDatabase("localhost/3050:c:/5f2a50c06b9c40cc83db938ec44d8bde.fdb");
        // dataSource.setDatabase("localhost/3050:C:\\Program Files (x86)\\IPP\\MetaGR Hunter\\base\\baseuser.fdb");
        dataSource.setDatabase("localhost/3050:C:\\B1.fdb");
            dataSource.setDescription("An example database of employees");
            dataSource.setType("TYPE4");
            //dataSource.setEncoding("ISO8859_1");
            dataSource.setEncoding("none");
            try {
                dataSource.setLoginTimeout(10);
                Connection conn = dataSource.getConnection("surgeon", "knife");
                return conn;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    public static void close(Connection conn, PreparedStatement ps) {
        try {
            if (conn != null) conn.close();
            if (ps != null) ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        try {
            if(conn!=null) conn.close();
            if(ps!=null) ps.close();
            if(rs!=null) rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行增删改的sql
     */
    public static int executeUpdate(String sql,Object...params){
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = FBJDBCUtils.getConn();
            pstmt = createPreparedStatement(conn,sql,params);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            FBJDBCUtils.close(conn,pstmt);
        }
        return 0;
    }

    private static  PreparedStatement  createPreparedStatement(Connection conn,String sql,Object...params) throws SQLException {
        conn = FBJDBCUtils.getConn();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        if( params != null  && params.length > 0 ){
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1,params[i]);
            }
        }
        return pstmt;
    }
    public static String convertBlobToString(Blob blob) {
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = blob.getBinaryStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "gbk"))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(System.lineSeparator());
            }
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }

        return stringBuilder.toString();
    }


   /*public static void main(String[] args) throws SQLException, IOException {
    Connection con = getConn();
       DatabaseMetaData metaData = con.getMetaData();

       // 获取数据库编码
       String characterSet = metaData.getExtraNameCharacters();
       System.out.println("Firebird Character Set: " + characterSet);
       //  PreparedStatement ps = createPreparedStatement(con, "SELECT * FROM issled where indissl = ?", "309317");
        PreparedStatement ps = createPreparedStatement(con, "SELECT * FROM image where ind = ?", "222");
    java.sql.ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        // Blob blob = rs.getBlob("GRAPH1");
        BufferedReader br = new BufferedReader(new InputStreamReader(rs.getBinaryStream("DATA"),"gbk"));//读取出来中文
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null)
        {
            sb.append(line);
        }
        System.out.println(sb.toString());

        Blob blob = rs.getBlob("DATA");
        InputStream inputStream = blob.getBinaryStream();
        byte[] data = new byte[(int) blob.length()];
        inputStream.read(data);
        String xmlString = new String(data);
        // 在这里可以使用XML解析库解析xmlString

        System.out.println(xmlString);

    }
        close(con, ps, rs);
}*/

    public static void main(String[] args) throws SQLException, IOException {
        Connection con = getConn();
        // PreparedStatement ps = createPreparedStatement(con, "SELECT * FROM issled where indissl = ?", "6");
        PreparedStatement ps = createPreparedStatement(con, "SELECT DATA FROM image where ind = ?", "222");
        java.sql.ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            // Blob blob = rs.getBlob("GRAPH1");
            Blob blob = rs.getBlob("DATA");
            ByteArrayOutputStream baos = new ByteArrayOutputStream((int) blob.length());
            InputStream is = blob.getBinaryStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            is.close();
            // 将ByteArrayOutputStream转换为byte数组
            byte[] data = baos.toByteArray();

            // 将byte数组转换为十六进制字符串
            StringBuilder hexBuilder = new StringBuilder();
            for (byte b : data) {
                String hex = Integer.toHexString(b & 0xFF).toUpperCase();
                if (hex.length() == 1) {
                    hexBuilder.append('0');
                }
                hexBuilder.append(hex);
            }
            String hexString = hexBuilder.toString();
            System.out.println (hexString);
            String str = hexString; // 要被分割的字符串
            String[] arr = str.split("1C0000000"); // 使用逗号作为分隔符进行切割
            System.out.println (arr.length);
            for (int i=0; i<arr.length; i++) {
                if(arr[i].length()>=160&&!(arr[i].substring(0,2).equals("00"))&&(arr[i].substring(12,14).equals("00"))){
                    if(arr[i].substring(0,2).equals("01")){//1级符号
                        System.out.println("x="+HexUtils.HexToDouble(HexUtils.reCoverHex(arr[i].substring(56,72))));
                        System.out.println(arr[i].substring(72,88)); // 输出每个元素
                        System.out.println("y="+HexUtils.HexToDouble(HexUtils.reCoverHex(arr[i].substring(72,88))));
                    }
                    if(arr[i].substring(0,2).equals("02")){//2级符号

                    }
                    if(arr[i].substring(0,2).equals("03")){//3级符号

                    }if(arr[i].substring(0,2).equals("04")){//4级符号

                    }if(arr[i].substring(0,2).equals("04")){//5级符号

                    }if(arr[i].substring(0,2).equals("06")){//6级符号

                    }



                }
            }
        }
        close(con,ps,rs);
    }
  /*  public static void main(String[] args) throws SQLException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH); // HH 也可以换成 kk
        executeUpdate("update pacient set BIRTHDATE = ?,firstname = ? where ind= ?",  new Timestamp(new java.util.Date().getTime()),"111", 5749);
    }*/

/*    public static void main(String[] args) throws SQLException, IOException {
        static Map<String,String>splitByteArr(bytell data, int blocksize){int blockCout =(data.length+blockSize-1)/blockSize:
            bytel] range = null；
            String str= String str2；
            for(int i=1:i<10:i+){
                int idx=(i-1)* blocksize:
                range = Arrays.copyOfRange(data, idx, to: idx + blockSize)if(StringUtils.isBlank(str)){
                    str = doubleToStr(brtes2Double(range)):}else{
                    str = str +”+ doubleToStr(brtes2Double(range)):
                    for(int i=9:i<blockCount;i++){
                        int idx =(i)* blockSize:
                        range = Arrays.copyOfRange(data, idx, to: idx + blockSize)
                        if(StringUtils.isBlank(str21)1
                        BasicDataUtilsstr2= doubleToStr(bypublic static double bytes2Double(bytel arr)}else {str2=str2+,”+ doubleToStr(brtes2Double(range)):

                        int end =-1:
                        if(data.length%blockSize=0){
                            end = data.length;
                        } else {
                            end= data.length%blockSize+blockSize*(blockCount -1):
                            range = Arrays.copyOfRange(data,(blockCount-1)*blockSize, end);str = str ++ doubleToStr(bytes2Double(range)):Map<String,String>map = new HashMap<>():
                            map.put( n ,str):
                            map.put('s ,str2):
                            return map;
    }*/
}
